import { defineComponent, h, ref } from 'vue';

import { cloneDeep } from '@vben/utils';

import AdvancedFilterComponent from './index.vue';

export function useAdvancedFilter(options = {}) {
  const advancedFilterRef = ref();

  const api = {
    ...options,
    getFormValues: () => {
      return advancedFilterRef.value?.getFormValues();
    },
    clearAllExposed: () => {
      return advancedFilterRef.value?.clearAllExposed();
    },
    filterParams: (formValues: any, values: any) => {
      if (values.length > 0) {
        const list = cloneDeep(values);
        formValues.params = {};
        for (const item of list) {
          formValues.params[item.fieldName] = item.value;
          formValues.params[`${item.fieldName}-op`] = item.condition;
        }
      }

      for (const key in formValues) {
        if (/^_.*_$/.test(key)) {
          // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
          delete formValues[key];
        }
      }

      return formValues;
    },
  };

  const extendedApi = api;
  const AdvancedFilter = defineComponent(
    (props: any, { attrs, slots }) => {
      return () =>
        h(
          AdvancedFilterComponent,
          {
            ref: advancedFilterRef,
            ...props,
            ...attrs,
            filterApi: extendedApi,
          },
          slots,
        );
    },

    {
      name: 'AdvancedFilter',
      inheritAttrs: false,
    },
  );

  return [AdvancedFilter, extendedApi] as const;
}
